const express = require('express')
const app = express()
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
var session = require('express-session')
// var cookieParser = require("cookie-parser")

const config = {
  db: "mongodb://localhost/test"
}
var User = require("./db/user")
var Comment = require("./db/comment")
app.set('view engine', 'ejs')
app.set('views', __dirname + "/public")


mongoose.set('debug', true)
// 连接mongodb
mongoose.connect(config.db, {
  useMongoClient: true
})
mongoose.connection.on('disconnected', () => {
  mongoose.connect(config.db)
})
mongoose.connection.on('error', err => {
  console.log(err)
})
mongoose.connection.on('open', async => {
  console.log('connected to ' + config.db)
})

app.use(session({
  secret: 'keyboard cat',
  cookie: {
    maxAge: 60000
  },
  saveUninitialized: false,
  resave: false
}))

app.use(bodyParser.urlencoded({
  extended: false
}))
app.use(bodyParser.json())
app.use(signinReq)

function signinReq(req, res, next) {
  console.log(req.session.loginedIn);
  if (req.session.loginedIn) {
    res.locals.authenticated = true
    User.findOne({
      _id: req.session.loginedIn
    }, (err, data) => {
      if (err) {
        next(err)
      } else {
        res.locals.user = data
        next()
      }
    })
  } else {
    res.locals.authenticated = false
    next()
  }

}
app.get('/', (req, res) => {
  res.render('index')
})
// app.get('/', function(req, res, next) {
//   if (req.session.views) {
//     req.session.views++
//     res.setHeader('Content-Type', 'text/html')
//     res.write('<p>views: ' + req.session.views + '</p>')
//     res.write('<p>expires in: ' + (req.session.cookie.maxAge / 1000) + 's</p>')
//     res.end()
//   } else {
//     req.session.views = 1
//     res.end('welcome to the session demo. refresh!')
//   }
// })
app.get('/signin', (req, res) => {
  res.render('signin', {
    signupEmail: req.params.signupUser
  })
})
app.post("/signin", function(req, res) {
  var body = req.body
  User.findOne({
    user: req.body.user
  }, (err, data) => {
    if (err) console.log(err)
    else {
      if (data) {
        if (data.password == body.password) {
          console.log("登录成功");
          req.session.loginedIn = data._id
          req.session.save(function(err) {
            console.log(req.session.loginedIn)
            res.redirect("/")
          })
        } else {
          console.log('密码不正确')
        }
      } else {
        console.log('用户不存在')
      }
    }
  })
})
app.post('/signup', (req, res) => {
  console.log(req.body)
  User.findOne({
    user: req.body.user
  }, (err, data) => {
    if (err) {
      console.log(err)
    } else {
      if (data) {
        console.log("该用户已经注册过")
      } else {
        var user = new User({
          user: req.body.user,
          password: req.body.password
        })
        user.save()
        res.redirect("/signin/" + req.body.user)
      }
    }
    console.log(data)
  })

})
app.get('/logout', function(req, res) {
  req.session.loginedIn = null
  res.redirect('/')
})
app.get('/signup', (req, res) => {
  res.render('signup')
})
app.get('/list', function(req, res) {
  User.count(function(err, count) {
    if (count > 10) {

    } else {
      User.find({}, (err, data) => {
        console.log(data)
        res.render('list', {
          list: data
        })
      })
    }
  })
})
app.get('/comment', (req, res) => {
  Comment.find({})
    .populate(['user']).exec(function(err, data) {
      if (err) {
        console.log(err)
      } else {
        console.log(data)
        res.render('comment', {
          list: data
        })
      }
    })
})
app.post('/comment',(req,res)=>{
  console.log(req.session.loginedIn);
  var comment=new Comment({
    content:req.body.content,
    user:"5a097f0890d19d2c60394d4a"
  })
  comment.save()
})
app.listen(3000)
